import { useState, useEffect, useRef } from 'react';
import { Table, Tag, Space, Modal, Form, Input, Button, Radio } from 'antd';
import 'antd/dist/antd.css'
import axios from 'axios'
import moment from 'moment'
import ExportJsonExcel from 'js-export-excel'

// setFiledValue
// getFiledValue
const App = () => {

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      render: text => <a>{text}</a>,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '数量',
      dataIndex: 'skuCount',
      key: 'skuCount',
    },
    {
      title: '图片',
      dataIndex: 'imgUrl',
      key: 'imgUrl',
      render: imgUrl => {
        return <img src={imgUrl} width="50" height="50"/>
      }
    },
    {
      title: 'Key',
      key: 'key',
      dataIndex: 'key',
      render: tags => (
        <>
          <Tag color={tags % 2  ? 'geekblue' : 'green'} key={tags}>
            {tags % 2 ? "系统": "非系统"}
          </Tag>
        </>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => {
            setBtnMsg('edit')
             form.setFieldsValue({...record})
             setGoodsItem({...record})
             setIsModalVisible(true);
            // console.log('record:,,, ', record)
          }}>编辑 </a>
          <a onClick={() => {
             deleteGoodsItem(record)
          }}>删除</a>
        </Space>
      ),
    },
  ];

  const [data, setData] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm(); // 实例
  const [goodsItem, setGoodsItem] = useState({})
  const [btnMsg, setBtnMsg] = useState('edit')
  const [option, setOption] = useState({})

  useEffect(() => {
    getGoodsList()
  }, [])

  // 下载表格数据
  const getExcel = () => {
    /**
        createTime: "2021-03-11"
        id: 93
        imgUrl: ""
        key: 1
        price: "802300"
        skuCount: 41141
        skuId: "58215aa0-8244-11eb-b02e-75c06203ddb5"
     */
    let opt = {}
    opt.fileName='商品表'
    opt.datas = [
      {
        sheetData: data,
        sheetName:'商品表',
        sheetFilter: ["id", "imgUrl", 'createTime', 'price', 'skuCount', 'skuId'],
        sheetHeader: ['ID', '图片', '时间', '价格', '数量', '商品ID'],
      }
    ]
    // setOption(opt)

    const toExcel = new ExportJsonExcel(opt);
    toExcel.saveExcel()
  }


  // 1. 查询：请求数据函数
  const getGoodsList = async () => {
    const response = await axios.get('http://47.101.45.245:7005/api/findGoods')
    console.log('response....:', response)
    response.data.data.forEach((item, index) => {
      item.key = index+1;
      item.createTime = moment().format('YYYY-MM-DD')
    })
    console.log('res.........:', response.data.data)
    setData(data => response.data.data)
  }

  // 2. 修改：修改数据接口 api/updateGoods/3
  const updateGoodsItem = async (item) => {
    const response = await axios.put(`http://47.101.45.245:7005/api/updateGoods/${item.id}`, {
      ...item
    })
    getGoodsList()
  }

  // 3. 添加：添加数据接口
  const addGoodsItem = async (item) => {
    const response = await axios.post(`http://47.101.45.245:7005/api/addGoods/`, {
      ...item, skuCount: Number(item.skuCount)
    })
    getGoodsList()
  }

  // 4.删除：删除接口
  const deleteGoodsItem = async (item) => {
    const response = await axios.delete(`/api/deleteGoods/${item.id}`, {
      ...item, skuCount: Number(item.skuCount)
    })
    getGoodsList()
  }

  // 弹出框确认事件
  const handleOk = () => {
    const formItem = form.getFieldsValue()
    const item = {...goodsItem, ...formItem}
    if (btnMsg === 'edit') {
      // console.log(item, 'item')
      updateGoodsItem(item)
    } else {
      addGoodsItem(item)
    }
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return <div>

      <Button onClick={() => {
        setBtnMsg('add')
        setIsModalVisible(true);
      }}>添加数据</Button>

      <Button onClick={() => {
        getExcel()
      }}>下载excel</Button>

      <Modal title="Basic Modal" visible={isModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}>
      <Form
        form={form}
        initialValues={{ }}
      >

        <Form.Item label="图片" name="imgUrl">
          <Input placeholder="input placeholder" />
        </Form.Item>
        <Form.Item label="价格" name="price">
          <Input placeholder="input placeholder" />
        </Form.Item>
        <Form.Item label="数量" name="skuCount">
          <Input placeholder="input placeholder" />
        </Form.Item>

      </Form>
      </Modal>
     <Table columns={columns} dataSource={data} />
  </div>
}


export default App;
